package org.lex.swing.plaf.widget;

import java.awt.Component;
import java.awt.event.KeyEvent;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.LookAndFeel;

import org.lex.swing.plaf.util.LookAndFeelUtils;

public class LookAndFeelMenu extends JMenu {
	private Component[] components = null;
	private ButtonGroup group = null;

	public LookAndFeelMenu() {
		super("Theme");
		this.setMnemonic(KeyEvent.VK_T);
		this.createMenu();
	}

	public LookAndFeelMenu(Component... components) {
		this();
		this.components = components;
	}

	private void createMenu() {
		// add installed look and feel
		this.addInstalledLookAndFeel();
	}

	private void addInstalledLookAndFeel() {
		// add metal look and feel first
		MetalMenu metal = new MetalMenu(components);
		this.addToGroup(metal.getChildern());
		this.add(metal);
		// add other installed look and feels
		LookAndFeel[] lnfs = LookAndFeelUtils.getInstalledLookAndFeels();
		for (LookAndFeel lnf : lnfs) {
			if (null == lnf)
				continue;
			String name = lnf.getName();
			if ("metal".equalsIgnoreCase(name))
				continue;
			this.addLookAndFeel(lnf);
		}
	}

	private void addLookAndFeel(LookAndFeel lnf) {
		if (null == lnf)
			return;
		JMenuItem item = new LookAndFeelRadioMenuItem(lnf, components);
		this.getGroup().add(item);
		this.add(item);
	}

	private void addToGroup(AbstractButton[] buttons) {
		if (null == buttons || 0 == buttons.length)
			return;
		for (AbstractButton b : buttons)
			this.getGroup().add(b);
	}

	private ButtonGroup getGroup() {
		if (null == group) {
			this.group = new ButtonGroup();
		}
		return group;
	}
}
